<template>
  <div>
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="楼层" prop="floors">
        <el-select multiple v-model="queryParams.floors" clearable placeholder="请选择">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="选择时间范围" prop="startTime" label-width="100">
          <el-date-picker
          v-model="queryParams.startTime"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期">
          </el-date-picker>
      </el-form-item>
    
      <el-form-item label="统计方案" prop="deptName">
        <el-select v-model="queryParams.range" clearable placeholder="请选择">
          <el-option
            v-for="item in options1"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-button type="primary" @click="show">更新图表</el-button>
    </el-form>
    <div v-loading="loading" :style="{ width: width, height: height ,margin:'80px auto'}">
      <div :id="chartId" :style="{ width: width, height: height }"></div>
    </div>
  </div>
</template>

<script>
let moment = require('moment');

export default {
  name: 'fq1',
  data() {
    return {
      chart:'',
      loading:true,
      list:[],
      datax:[],
      dataAll:[],
      graph:{
        data4th:[],
        data5th:[],
        data6th:[],
        data7th:[],
        data8th:[],
        data9th:[],
        data10th:[],
        data11th:[],
      },
      chartId: 'main',
      width: 1500 + 'px',
      height: 500 + 'px',
      queryParams: {
        floors: [],
        startTime:[],
        range: 'mint'
      },
      options: [
        {
          value: '4th',
          label: '4层',
        },
        {
          value: '5th',
          label: '5层',
        },
        {
          value: '6th',
          label: '6层',
        },
        {
          value: '7th',
          label: '7层',
        },
        {
          value: '8th',
          label: '8层',
        },
        {
          value: '9th',
          label: '9层',
        },
        {
          value: '10th',
          label: '10层',
        },
        {
          value: '11th',
          label: '11层',
        },
      ],
      options1:[
        {
          value: 'day',
          label: '显示年月日',
        },
        {
          value: 'mint',
          label: '显示时分秒',
        },
      ]
    }
  },
  async created(){

    let 
        startTime = moment(new Date()).format("YYYY-MM-DD"),
        endTime = moment(startTime).subtract(3, "days").format("YYYY-MM-DD"),
        floors=[];
    await this.$axios.post('api/realTest/findByFloor?floors='+ floors + '&startTime='+ startTime + '&endTime='+ endTime ).then((res)=>{
          this.list = res.data.data
        }).then(()=>{
          this.showmint()
        }).then(()=>{
          this.createChart()
        }).then(()=>{
          this.loading = false
        })
    },
  methods: {
    show(){
      let {floors,startTime} = this.queryParams
      let a = startTime.length?moment(startTime[0]).format('YYYY-MM-DD'):''
      let b = startTime.length?moment(startTime[1]).format('YYYY-MM-DD'):''
      if(moment(b).diff(moment(a),'day')>=5){
        alert('请选择五天以内的数据')
      }else{
        this.loading = true
      this.$axios.post('api/test/findByFloor?floors='+ floors + '&startTime='+a + '&endTime='+ b).then((res)=>{
        this.list = res.data.data
        }).then(()=>{
          if(this.queryParams.range === 'day'){
            // this.showDay()显示天
            this.showData(0,10)
          }else{
            // this.showmint()显示时分秒
            this.showmint()
          }
        }).then(()=>{
          this.createChart()
        }).then(()=>{
          this.loading = false
        })
      }
    },

    showData(l,r){
      if (this.chart != null && this.chart != "" && this.chart != undefined) {
        this.chart.dispose();//销毁
      }
      let data = JSON.parse(JSON.stringify(this.list))
      //x轴数据
      let dx = new Map()
      for(let i of data){
        if(!dx.has(i.time.slice(l,r))){
          dx.set(i.time.slice(l,r),i.temp)
        }else{
          dx.set(i.time.slice(l,r),dx.get(i.time.slice(l,r))+i.temp)
        }
      }
      let map = new Map()
      for(let i of data){
        if(!map.has(i["floor"])){
          map.set(i["floor"],new Map().set(i['time'].slice(l,r),i.temp))
        }else{
          let t = map.get(i["floor"])
          if(t.has(i['time'].slice(l,r))){
            t.set(i['time'].slice(l,r),t.get(i['time'].slice(l,r))+i.temp)
          }else{
            t.set(i['time'].slice(l,r),i.temp)
          }
        }
      }
      //清空上次缓存数据，
      this.graph = {}
      this.datax = [...dx.keys()]
      this.dataAll = [...dx.values()].map(i => Math.floor(i/24))
      let hasTime = [...map.keys()]
      for(let i of hasTime){
        this.graph['data'+ i] = [...map.get(i).values()].map(j=> Math.floor(j/24))
      }
      console.log(this.graph);
    },
    showmint(){
      if (this.chart != null && this.chart != "" && this.chart != undefined) {
        this.chart.dispose();//销毁
      }
  //方法1    
      // let data = JSON.parse(JSON.stringify(this.list))
      // console.time('方法一');
      // let mounth = new Map()
      // let dataAll = {}

      // let graphs = {}
      // for(let i = 4;i<12;i++){
      //   graphs['data'+i+'th'] = Array(96).fill(0)
      // }
      // let s = "00:00:00"
      // let map = new Map()
      // for(let i=0;i<96;i++){
      //   dataAll[s] = 0
      //   map.set(s,new Map())
      //   s = moment(s,"HH:mm:ss").add(15, 'm').format("HH:mm:ss")
      // }
      // map.set("24:00:00",mounth)
      // dataAll["24:00:00"] = 0
      // let timeMap = [...map.keys()]
      // let lenM = timeMap.length
      // for(let i of data){
      //   let t = i.time.slice(11,19)
      //   for(let j = 0;j<lenM;j++){
      //     if(moment(t,"HH:mm:ss").isBetween(moment(timeMap[j]+'.111',"HH:mm:ss.SSS"),moment(timeMap[j+1]+'.111',"HH:mm:ss.SSS",null, '()'))){
      //         map.get(timeMap[j]).has(i.floor)?map.set(timeMap[j],map.get(timeMap[j]).set(i.floor,map.get(timeMap[j]).get(i.floor) + i.temp)):
      //         map.set(timeMap[j],map.get(timeMap[j]).set(i.floor,i.temp))
      //         //x轴总量
      //         graphs['data'+ i.floor][j] =  graphs['data'+ i.floor][j] + i.temp
      //         dataAll[timeMap[j]] += i.temp 
      //         break
      //       }
      //   }
      // }
      // //  //清空数据
      // this.graph = {}
      // this.graph = graphs
      // this.datax = [...map.keys()]
      // this.dataAll = Object.values(dataAll)
      // console.timeEnd('方法一')
      // console.log(graphs);
//方法2：
      let data = JSON.parse(JSON.stringify(this.list))
      console.time('方法二');
      let obj = {}
      let s = "00:00:00"
      for(let i=0;i<96;i++){
        obj[s] = 0
        s = moment(s,"HH:mm:ss").add(60, 'm').format("HH:mm:ss")
      }
      obj["23:59:59"] = 0
      let arr = Object.keys(obj)
      let lenA = arr.length
      let dataMap = new Map()
      for(let i = 4;i<12;i++){
        let s = JSON.parse(JSON.stringify(obj))
        dataMap.set(i+'th', s)
      }
      let floorD = [...dataMap.keys()]
      let dataAll = JSON.parse(JSON.stringify(obj))
      for(let i of data){
        let t = i.time.slice(11,19)
        for(let j of floorD){
          if(i.floor === j){
            let ob = dataMap.get(j)
            for(let r = 0;r<lenA;r++){
              if(moment(t,"HH:mm:ss").isBetween(moment(arr[r]+'.111',"HH:mm:ss.SSS"),moment(arr[r+1]+'.111',"HH:mm:ss.SSS",null, '()'))){
                ob[arr[r+1]] = ob[arr[r+1]] + i.temp
                dataAll[arr[r+1]] += i.temp
                break
              }
            }
          }
        }
      }
       //清空数据
      this.graph = {}
      this.datax = arr
      this.dataAll = Object.values(dataAll).map(i => Math.floor(i/60))
      for(let i of floorD){
        this.graph['data'+i] = Object.values(dataMap.get(i)).map(j => Math.floor(j/60))
      }
      console.timeEnd('方法二')
    },

    createChart() {
      // 基于准备好的dom，初始化echarts实例
      this.chart = this.$echarts.init(document.getElementById(this.chartId));
      // 指定图表的配置项和数据
    var option = {
    title: {
        text: '折线图堆叠'
    },
    tooltip: {
        trigger: 'axis'
    },
    legend: {
        data: ['4th', '5th', '6th', '7th', '8th','9th','10th','11th',"总量"],
        selected:{
          '4th': this.graph['data4th'] && !this.graph['data4th'].every(i => i==0),
          '5th': this.graph['data5th'] &&!this.graph['data5th'].every(i => i==0),
          '6th': this.graph['data6th'] &&!this.graph['data6th'].every(i => i==0),
          '7th': this.graph['data7th'] &&!this.graph['data7th'].every(i => i==0),
          '8th': this.graph['data8th'] &&!this.graph['data8th'].every(i => i==0),
          '9th': this.graph['data9th'] &&!this.graph['data9th'].every(i => i==0),
          '10th':this.graph['data10th'] && !this.graph['data10th'].every(i => i==0),
          '11th': this.graph['data11th'] &&!this.graph['data11th'].every(i => i==0),
          '总量': this.dataAll && !this.dataAll.every(i => i==0)
        }
    },
    grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
    },
    toolbox: {
        
    },
    xAxis:[ {
        type: 'category',
        boundaryGap: false,
        data: this.datax,
        axisLabel:{
          rotate:90,
        },
        show:false
    },
    {
        type: 'category', 
        data: this.datax,
        axisLabel:{
          rotate:90,
        },
        position : 'bottom',
        axisTick: {
            length:20
        }
    },

    ],
    yAxis: {
        type: 'value'
    },
    series: [
        {
            name: '4th',
            type: 'line',
            // stack: '总量',
            data: this.graph.data4th,
            symbol:'none'
        },
        {
            name: '5th',
            type: 'line',
            // stack: '总量',
            data: this.graph.data5th,
            symbol: 'none'
        },
        {
            name: '6th',
            type: 'line',
            // stack: '总量',
            data: this.graph.data6th,
            symbol: 'none'
        },
        {
            name: '7th',
            type: 'line',
            // stack: '总量',
            data:this.graph.data7th,
            symbol: 'none'
        },
        {
            name: '8th',
            type: 'line',
            // stack: '总量',
            data: this.graph.data8th,
            symbol: 'none'
        },
        {
            name: '9th',
            type: 'line',
            // stack: '总量',
            data: this.graph.data9th,
            symbol: 'none'
        },
        {
            name: '10th',
            type: 'line',
            // stack: '总量',
            data: this.graph.data10th,
            symbol: 'none'
        },
        {
            name: '11th',
            type: 'line',
            // stack: '总量',
            data: this.graph.data11th,
            symbol: 'none'
        },
        {
            name: '总量',
            type: 'line',
            // stack: '总量',
            data: this.dataAll,
            symbol: 'none'
        }
    ]
};
      this.chart.setOption(option);
    }
  }
 
}
</script>

<style scoped>
.el-row {
  margin-bottom: 20px;
}
.el-col {
  border-radius: 4px;
}
.bg-purple-dark {
  background: #99a9bf;
}
.bg-purple {
  background: #d3dce6;
}
.bg-purple-light {
  background: #e5e9f2;
}
.grid-content {
  border-radius: 4px;
  min-height: 36px;
}
.row-bg {
  padding: 10px 0;
  background-color: #f9fafc;
}
</style>
